﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P4114Controller : ControllerBase
    {
        /// <summary>
        /// IA 单增加
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> Create(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            string ordernumber = objpram["ordernumber"].ToString();
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new MQException("401","请求的用户名或密码为空！");
                }
                //OAuthController oAuth = new OAuthController();
                //oAuth.GetToken(objpram);
                //if (string.IsNullOrWhiteSpace(SomeHandler.GetToken(username)))
                //{
                //    throw new MQException("401","验证失败，请检查用户名密码是否正确！");
                //}
                //string token = SomeHandler.GetToken(username);

                string token = SomeHandler.GetToken(username, password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }



                Console.WriteLine("新增IA单据");

                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();
                foreach (DataRow dr in new BLL.orderHandler().GetOrder(ordernumber)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "31", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "6", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "80", value = "PRI", command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "9", value = "Test1521", command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "10", value = "  ZGZ0200241", command = "SetGridCellValue" });

                    gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });

                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                            new FSREvent() { controlID="177", command="SetControlValue",value= "IA" },
                                            new FSREvent() { controlID="173", command="SetControlValue",value= lastrow["BU"].ToString() },
                                            new FSREvent() { controlID="171", command="SetControlValue",value= $"{lastrow["ordernumber"].ToString()}" },
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P4114_W4114A",
                    version = "ZJDE0001",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4114_W4114A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string IAno = obj["fs_P4114_W4114A"]["data"]["z_DOC_167"]["value"].ToString();
                    Console.WriteLine($"生成IA单:{IAno}");
                    execresult.Result = IAno;
                }
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            return execresult;
        }


        /// <summary>
        /// F6单据
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreateF6(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            string orderid = objpram["orderid"].ToString();
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;


            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                token = SomeHandler.GetToken(username, password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增F6单据 {orderid}");
                #region 打开IT单列表,点击新增
                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    formName = "P4114_W4114B",
                    version = "MBR002",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    formActions = new FormActionsCollection
                    (
                        new FSREvent[]
                        {
                            new FSREvent() { controlID="6", command="DoAction"  }
                        }
                    )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P4114_W4114B",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                #endregion
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4114_W4114A"))
                {

                    List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                    FormActionsCollection fs = new FormActionsCollection();
                    v_blStockadjust lastrow = new v_blStockadjust();
                    List<v_blStockadjust> list = new BLL.orderHandler().GetF6Order(orderid);
                    if (list.Count <= 0)
                        throw new MQException("404", "无数据产生，请检查是否需要生成F6单！");

                    foreach (v_blStockadjust dr in list)
                    {
                        gridcolumnCollection col = new gridcolumnCollection();
                        col.Add(new gridcolumnevent() { columnID = "31", value = dr.itemnumber, command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "6", value = dr.quantity.ToString() , command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "80", value = dr.LOCN.Trim(), command = "SetGridCellValue" });
                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });


                        lastrow = dr;
                    }
                    GridAction _gridAction = new GridAction();
                    _gridAction.gridID = "1";
                    _gridAction.gridRowInsertEvents = gridrows;

                    //fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                    //fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                    ActionRequest actionRequest = new ActionRequest()
                    {
                        formOID = "W4114A",
                        formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {

                                            new FSREvent() { controlID="173", command="SetControlValue", value=lastrow.BU},
                                            new FSREvent() { controlID="171", command="SetControlValue", value=lastrow.sys_remark},
                                            new FSREvent() {
                                                            controlID ="1.0",
                                                            command ="SelectRow",
                                                            gridAction =_gridAction
                                                            },

                                            new FSREvent() { controlID="4", command="DoAction"  }
                                         }
                                     )
                                 ,
                        stopOnWarning = "false"
                    };
                    asrequest = new ApplicationStackRequest()
                    {
                        outputType = "VERSION2",
                        allowCache = true,
                        action = "execute",
                        actionRequest = actionRequest,
                        stackId = response.stackId,//上一次返回的值
                        stateId = response.stateId,
                        rid = response.rid
                    };

                    response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    needclose = true;
                    stackId = response.stackId;
                    stateId = response.stateId;
                    rid = response.rid;

                    System.Threading.Thread.Sleep(500);
                    if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4114_W4114A"))
                    {
                        JObject obj = response.ToJObject();
                        //应该查询到数据
                        string IAno = obj["fs_P4114_W4114A"]["data"]["z_DOCO_204"]["value"].ToString();
                        Console.WriteLine($"{DateTime.Now.ToString()} 生成F6单:{IAno}");
                        execresult.Result = $"F6{IAno}";
                        execresult.Message = response.JsonString;
                    }
                }
            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    formOID = "W4114A"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                }
                #endregion
            }
            return execresult;
        }
    }
}